import 'dart:convert';
import 'dart:math';
import 'package:frontend/models/global.dart';
import 'package:frontend/models/groupMessages.dart';
import 'package:frontend/models/personalMessages.dart';
import 'package:frontend/reqs/requests.dart';
import 'package:glob/glob.dart';

import 'package:flutter/material.dart';
import 'package:flutter_chat_types/flutter_chat_types.dart' as types;
import 'package:flutter_chat_ui/flutter_chat_ui.dart';

// For the testing purposes, you should probably use https://pub.dev/packages/uuid.
String randomString() {
  final random = Random.secure();
  final values = List<int>.generate(16, (i) => random.nextInt(255));
  return base64UrlEncode(values);
}

class groupChattingPage extends StatefulWidget {
  groupChattingPage(int group_id, {super.key}) {
    Global.profile.group_id = group_id;
  }

  @override
  State<groupChattingPage> createState() => _groupChattingPageState();
}

class _groupChattingPageState extends State<groupChattingPage> {
  List<types.TextMessage>? _messages;
  final _user = types.User(id: Global.profile.user!.id.toString());

  @override
  Widget build(BuildContext context) => Scaffold(
      appBar: AppBar(
        title: Text("聊天"),
      ),
      body: FutureBuilder<GroupMessages?>(
          future: fetchGroupMessages(Global.profile.group_id!),
          builder: (context, snapshot) {
            return Chat(
              messages: _messages == null
                  ? _messages = [
                      for (int i = 0;
                          i < snapshot.data!.messages.length;
                          ++i)
                        types.TextMessage(
                            author: types.User(
                                id: snapshot.data!.messages[i].sender_id
                                    .toString()),
                            createdAt: snapshot.data!.messages[i].time,
                            id: randomString(),
                            text: snapshot.data!.messages[i].message)
                    ]
                  : _messages!,
              onSendPressed: _handleSendPressed,
              user: _user,
            );
          }));

  void _addMessage(types.TextMessage message) {
    setState(() {
      _messages!.insert(0, message);
    });
  }

  void _handleSendPressed(types.PartialText message) {
    final textMessage = types.TextMessage(
      author: _user,
      createdAt: DateTime.now().millisecondsSinceEpoch,
      id: randomString(),
      text: message.text,
    );
    addGroupMessage(Global.profile.group_id!, Global.profile.user!.id,
        message.text, DateTime.now().microsecondsSinceEpoch);
    _addMessage(textMessage);
  }
}
